<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class UserModel{ 
    protected $CI;
    private $pageSize = 10;
    protected $timeoutminute = 1440; //默认24小时超时
    public function __construct(){
        $this->CI =& get_instance();
        $this->CI->load->database();
    }
    /**
     * [adminLogin description]
     * @return [type] [description]
     */
    public function adminLogin($account,$password){
        $info = $this->CI->db->get_where('user_base', array('account' => $account,'password'=>$password,'status'=>0,'role'=>'管理员'),1, 0); 
        $result = $info->row();
        log_message('info', 'adminLogin,result:'.json_encode($result));    
        if(!$result){
            return 2000;
        }
        // var_dump($result);exit;
        else{
            $this->CI->session->admin_user_id = $result->id; 
            return 0;

        }

    } 
    /**
     * [adminLogOut description]
     * @return [type] [description]
     */
    public function adminLogOut(){
        $this->CI->session->admin_user_id = 0; 
        return 0;

    }
    /**
     * [userLoginByAccount description]
     * @param  [type] $account  [description]
     * @param  [type] $password [description]
     * @return [type]           [description]
     */
    public function userLoginByAccount($account,$password,$message,$userId,$reqData=''){
        //1查询当前userid是否已经绑定过手机号
        $query = "SELECT id ,account,open_id,password,status FROM user_base where id = $userId and role = '普通用户' limit 1";
        $info = $this->CI->db->query($query);
        $object = $info->row();
        // var_dump($object);exit;
        if(!isset($object->id)){
            return 2000;
        }
        if($object->account){
            return 2008;
        }
        //2查询手机号是否已经绑定到其他账号上
        $query = "SELECT id ,account,open_id,password,status FROM user_base where account = $account and role = '普通用户' limit 1";
        $info = $this->CI->db->query($query);
        $object = $info->row();
        if(isset($object->id)){
            if($object->id==$userId){
                return 0; //就是当前用户，直接返回成功
            }
            else{
                return 2009;
            }
        }
        //3验证验证码是否有效
        $timeNow = date("Y-m-d H:i:s");

        $info = $this->CI->db->get_where('user_msg_verify', array('account' => $account,'code'=>$message,"time >$timeNow",'state'=>0,'platform'=>0),1, 0); 
        $object = $info->row();
        if(isset($object->id)){
            //4改为无效 
            $query = "update user_msg_verify set state = 1 where id = ".$object->id;
            $info = $this->CI->db->query($query);
             
            //5绑定手机号
            $query = "update user_base set account = $account where id = $userId";
            $info = $this->CI->db->query($query);

            //6修改邀请码
            if(isset($reqData['inviteCode']) && $reqData['inviteCode']){
                //被别人邀请来的
                $inviteCode = $reqData['inviteCode'];
                $query = "update user_extra set invite_code = $account 
                beinvited_code = $inviteCode
                where user_id = $userId";
            }
            else{
                //没有邀请人
                $query = "update user_extra set invite_code = $account 
                where user_id = $userId";
            }
            $info = $this->CI->db->query($query);
            return 0;
        }
        else{
            return 2010;
        }
    }

    /**
     * [addUser description]
     */
    public function addUser($openid,$session_key,$head,$nick){

        $query = "SELECT id FROM user_base where open_id = '$openid' and status = 0 limit 1";
        $info = $this->CI->db->query($query);
        $userResult = $info->row();
        // echo $userbind->id;exit;
        if(isset($userResult->id)){
            //存在，更新数据库sessionkey
            $query = "update user_base set session_key = '$session_key' where open_id = '$openid'";
            $info = $this->CI->db->query($query);
            $ret['status'] = 0;
            //旧的失效，添加新的session跟userid关系  
            $ret['out_data']['sf_session_key'] = $this->addSessionBody($userResult->id);
            return $ret;
        }
        else{
            //不存在，新建信息
            $this->CI->db->trans_start();
            {
                //1、user_base
                $query = "insert into user_base(open_id,session_key) values('$openid','$session_key')";
                $info = $this->CI->db->query($query);
                // echo json_encode($user);exit;
                if($this->CI->db->trans_status()==false){
                    $this->CI->db->trans_rollback();
                    $ret['status'] = 2002;
                    return $ret;
                }
            }
            {
                //2、user_extra
                $query = "select id from user_base where open_id = '$openid'";
                $info = $this->CI->db->query($query);
                $user = $info->row();
                $user_id = $user->id;
                $query = "insert into user_extra(user_id,nickname,avatar) values($user_id,'$nick','$head')";
                $info = $this->CI->db->query($query);
                // echo json_encode($user);exit;
                if($this->CI->db->trans_status()==false){
                    $this->CI->db->trans_rollback();
                    $ret['status'] = 2002;
                    return $ret;
                }
            }
            { 
                //3、第一次添加，新的session跟userid，超时时间对应关系
                $sf_session_key = $this->addSessionBody($user_id);
            }
            $this->CI->db->trans_complete();
            $ret['out_data']['sf_session_key'] = $sf_session_key;
            $ret['status'] = 0;
            return $ret;
        }
    }

    /**
     * [延长登录时间，所有涉及到后台的操作，都会有]
     * @return [type] [description]
     */
    public function updateLoginDeadline($userid,$sf_session_key,$sf_session_value){
        log_message('info', "updateLoginDeadline,userid:$userid,sf_session_key:$sf_session_key,sf_session_value:".json_encode($sf_session_value));    
        // echo $userid,$session_key;exit;
        $timeoutminute = $this->timeoutminute;
        $sf_session_value['deadline'] = date("Y-m-d H:i:s",strtotime("+$timeoutminute  minute"));
        // var_dump($session_key_value);exit;
        $sf_session_value = json_encode($sf_session_value);
        $this->CI->session->$sf_session_key = $sf_session_value; 

        //数据保存
        $query = $this->CI->db->get_where('sf_session_key', array('session_key' => $sf_session_key),1, 0); 
        // $query = "update session_key set session_key_value = '$session_key_value' where session_key = '$session_key'";
        $object = $query->row();
        log_message('info', "updateLoginDeadline,object:".json_encode($object));   
        if(isset($object->id)){
            //更新
            $status = $this->CI->db->set("session_key_value",$sf_session_value)->where("session_key",$sf_session_key)->update('sf_session_key');
        }
        else{
            //添加
            $temp = array(
                "session_key"=>$sf_session_key,
                "session_key_value"=>$sf_session_value,
            );
            $status = $this->CI->db->insert('sf_session_key', $temp);
        }
        return 0;
    }

    /**
     * [addSessionBody description]
     * @param [type] $userid [description]
     */
    public function addSessionBody($userid){
        $sf_session_key = $this->createSessionLey();
        $this->updateLoginDeadline($userid,$sf_session_key,array("user_id"=>$userid));
        return $sf_session_key;
    }
    /**
     * [生成第三方的sessionkey]
     * @return [type] [description]
     */
    private function createSessionLey(){
        srand(time()); 
        $rand = "SF".time().(mt_rand(1000000000,9999999999));
        // echo $rand;exit;
        return $rand;
    }

     /**
     * [loginStatus description]
     * @return [type] [description]
     */
    public function loginStatus($reqData){
        if(isset($reqData['sf_session_key']) &&$reqData['sf_session_key']){
            $sf_session_key = $reqData['sf_session_key'];
            // $sf_session_value = $this->CI->session->$sf_session_key;
            
            $query = $this->CI->db->get_where('sf_session_key', array('session_key' => $sf_session_key),1, 0); 
            $object = $query->row();
            $sf_session_value = isset($object->session_key_value)?$object->session_key_value:"";
            log_message('info', "loginStatus,sf_session_key:$sf_session_key,sf_session_value:$sf_session_value");    
            // var_dump($session_value);exit;
            $sf_session_value_arr = json_decode($sf_session_value,true);
            // var_dump($sf_session_value_arr);exit;
            if(isset($sf_session_value_arr['user_id']) && $sf_session_value_arr['user_id'] && isset($sf_session_value_arr['deadline']) && $sf_session_value_arr['deadline']){
                if($sf_session_value_arr['deadline']>=date("Y-m-d H:i:s")){
                    //1、登录还有效，更新超时时间，延长$this->timeoutminute分钟
                    // $this->CI->load->model("sessionKeyModel");
                    $this->updateLoginDeadline( $sf_session_value_arr['user_id'],$sf_session_key,$sf_session_value_arr);   
                    $ret['userId'] =  $sf_session_value_arr['user_id'];
                    $ret['status'] = 0;
                    return $ret;
                     
                }
                else{
                    log_message('info', 'loginStatus,login info is invalid');    
                    $ret['status'] = 2011;
                    return $ret;
                }
            }
            else{
                log_message('info', 'loginStatus,sf_session_value is null');      
                $ret['status'] = 2000;
                return $ret;
            }
        }
        else{
            log_message('info', 'loginStatus,sf_session_key  is null');                
            $ret['status'] = 1000;
            return $ret;
        }                
    }





    /**
     * [baseInfo description]
     * @param [type] $userid [description]
     */
    public function baseInfo($userId){
        $query = $this->CI->db->get_where('user_base', array('id' => $userId),1, 0); 
        $result = $query->result();
        if(isset($result[0]) && $result[0]->id){
            return $result[0];
        }
        else{
            return array();
        }
    } 
    /**
     * [extraInfo description]
     * @param [type] $userid [description]
     */
    public function extraInfo($userId){
        $query = $this->CI->db->get_where('user_extra', array('user_id' => $userId), 1, 0);
        $result = $query->result();
        // var_dump($result);exit;
        if(isset($result[0]) && $result[0]->id){
            return $result[0];
        }
        else{
            return array();
        }
    }    

    /**
     * [extraInfo description]
     * @param [type] $userid [description]
     */
    public function extraInfoBatch($userIdString){
        $query = $this->CI->db->get_where('user_extra', array('user_id in(' => $userIdString.")"));
        $result = $query->result();
        return $result;
    }   

    /**
     * [extraInfo description]
     * @param [type] $userid [description]
     */
    public function mixUserInfo($userId){
        $query = $this->CI->db
        ->select("base.account,extra.*")
        ->join("user_base as base","base.id = extra.user_id")
        ->get_where('user_extra as extra', array('base.id ' => $userId));
        $result = $query->row();
        return $result;
    }
     /**
     * [extraInfoByEmail description]
     * @param [type] $userid [description]
     */
    public function extraInfoByEmail($email){
        $query = $this->CI->db->get_where('user_extra', array('email' => $email), 1, 0);
        $result = $query->result();
        // var_dump($result);exit;
        if(isset($result[0]) && $result[0]->id){
            return $result[0];
        }
        else{
            return array();
        }
    }

     /**
     * [bindEmail description]
     * @param [type] $userid [description]
     */
    public function bindEmail($userId,$email){
        //有效，改成已验证的
        $status = $this->CI->db->set("email",$email)->where("user_id",$userId)->update('user_extra');
        return 0;
    }

      /**
     * [bindEmail description]
     * @param [type] $userid [description]
     */
    public function updateSchool($userId,$schoolName,$studentNo){
        $status = $this->CI->db
            ->set("school_name",$schoolName)
            ->set("school_no",$studentNo)
            ->set("school_status",0)
            ->where("user_id",$userId)->update('user_extra');
        return 0;
    }  

    /**
     * [bindEmail description]
     * @param [type] $userid [description]
     */
    public function updateIdentity($userId,$idNo,$idName,$idStatus){
        $status = $this->CI->db
            ->set("id_no",$idNo)
            ->set("id_name",$idName)
            ->set("id_status",$idStatus)
            ->where("user_id",$userId)->update('user_extra');
        return 0;
    }

    /**
     * [创建任务
     * {"name":"测试任务1","type":"平面设计","reward":"66","closedate":"","closetime":"","instruction":"这是任务需求","cover":"1.png;2.png","notes":"提交须知","numberrequirement":"要求100字","taskcount":"2","platform":""}
     * ]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function createTask($userId,$data){
        $retData['success'] = 0;
        $retData['fail'] = 0;
        //1检测
        if(!is_numeric($data['reward'])){
            $retData['status'] = 1003;
            return $retData;
        }
        if(!strtotime($data['closeDate'])){
            $retData['status'] = 1003;
            return $retData;
        }
        $success = 0;
        $fail = 0;
        $retData = array();
        for($i = 0;$i<$data['taskCount'];$i++){
            $temp = array(
                "user_id"=>$userId,
                "name"=>strip_tags($data['name']),
                "keyword"=>$this->createKeyWord(6),
                "type"=>strip_tags($data['type']),
                "reward"=>$data['reward'],
                "platform"=>$data['platform'],
                "cover"=>$data['cover'],
                "close_date"=>$data['closeDate'],
                "close_time"=>$data['closeTime'],
                "instruction"=>$data['instruction'],
                "notes"=>strip_tags($data['notes']),
                "number_requirement"=>strip_tags($data['numberRequirement']),
                "create_year"=>date("Y"),
                "create_date"=>date("Y-m-d"),
                "create_month"=>date("m"),
            );
            $ret = $this->CI->db->insert('task', $temp);
            log_message("info","createTask,userid:$userId,ret:$ret,temp:".json_encode($temp));
            if($ret){
                // $lastId = $this->CI->db->insert_id();
                // $logData = array(
                //     "task_obtain_id"=>$userId,
                // );
                // $logRet = $this->CI->db->insert('task_obtain_log', $logData);
                // log_message("info","createTask,userid:$userId,logRet:$logRet,logData:".json_encode($logData));
                // if($logRet){
                    $success++;
                // }
            }
            else{
                $fail++;
                
            }
        }
        $retData['success'] = $success;
        $retData['fail'] = $fail;
        $retData['status'] = 0;
        return $retData;

    }
    /**
     * [createKeyWord description]
     * @return [type] [description]
     */
    private function createKeyWord($len){
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
        mt_srand(10000000*(double)microtime());  
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {  
            $str .= $chars[mt_rand(0, $lc)];  
        }  
        return $str;  
    }

    /**
     * [adminUserList description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function adminUserList($data){
        $column = "base.id,base.account,base.status
            ,extra.nickname as nick,extra.sex,extra.avatar as head,extra.email,extra.id_no as idNo
            ,extra.id_name as idName,extra.id_status as idStatus
            ,extra.school_name as schoolName,extra.school_no as schoolNo,extra.school_status as schoolStatus
            ,extra.school_time as schoolTime";
        $totalColumn = "count(base.id) as totalcount";
        $fileterArray = array(
            'base.status' => 0,
            'base.role' => '普通用户',            
        );   
        //过滤昵称
        if(isset($data['nick']) && $data['nick']){
            $fileterArray['extra.nickname like'] = '%'.$data['nick'] .'%';
        }
        //过滤手机号
        if(isset($data['account']) && $data['account']){
            $fileterArray['base.account like'] = '%'.$data['account'] .'%';
        }
        //过滤学校审核状态
        if(isset($data['schoolStatus']) && $data['schoolStatus']>=0 &&$data['schoolStatus']!=''){
            $fileterArray['extra.school_status'] = $data['schoolStatus'];
        }        
        $start = ($data['page']-1)>=0?($data['page']-1)*$data['size']:0;
        $query = $this->CI->db->select($column)->join("user_extra as extra",'extra.user_id = base.id')->order_by('base.id', 'asc')->get_where('user_base as base', $fileterArray, $data['size'], $start);
        $result = $query->result(); 

        $totalQuery = $this->CI->db->select($totalColumn)->join("user_extra as extra",'extra.user_id = base.id')->get_where('user_base as base', $fileterArray, 1, 0);
        $totalResult = $totalQuery->row();
        $ret['data'] = $result;
        $ret['out_data']['totalCount'] = isset($totalResult->totalcount)?$totalResult->totalcount:0;
        $ret['status'] = 0;
        return $ret;
    }  

    /**
     * [schoolIdentify description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function schoolIdentify($userId,$schoolStatus){
       
        $query = $this->CI->db->select('id,school_status')->get_where('user_extra', ['user_id'=>$userId], 1, 0);
        $result = $query->row(); 
        $ret['status'] = 1000;
        if($result){
            // var_dump($result);exit;
            if($result->school_status==0){
                $this->CI->load->model("noticeModel");
                if($schoolStatus==1){
                    //成功                    
                    $this->CI->noticeModel->addNotice($userId,1,$userId,'您的身份审核通过');
                    $this->CI->db->set("school_status",1)->where("user_id",$userId)->update('user_extra');

                }
                else{
                    //失败
                    $this->CI->noticeModel->addNotice($userId,1,$userId,'您的身份审核未通过');
                    $this->CI->db->set("school_status",2)->where("user_id",$userId)->update('user_extra');
                }
                $ret['status'] = 0;
            }
            else{
                $ret['status'] = 2021;
            }
        }
        return $ret;
    } 

    /**
     * [adminConfirmTask($admin_user_id,$data); description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function adminConfirmTask($admin_user_id,$data){
        //1任务领取的状态
        $query = $this->CI->db->select('id,status,task_id,user_id,deposit,left_deposit')->get_where('task_obtain', ['id'=>$data['obtainId']], 1, 0); 
        $obtainResult = $query->row();  
        // echo  $this->CI->db->last_query();
        if(!$obtainResult || is_null($obtainResult)) {
            $ret['status'] = 3000;
            return $ret;
        }
        if($obtainResult->status!=1){ //用户尚未申请
            $ret['status'] = 3001;
            return $ret;
        }

        //2判断任务状态
        $query = $this->CI->db->select('id,status')->get_where('task', ['id'=>$obtainResult->task_id], 1, 0);
        $taskResult = $query->row();  
        if(!$taskResult || is_null($taskResult)) {
            $ret['status'] = 3000;
            return $ret;
        }
        if($taskResult->status!=1){ //不在进行中
            $ret['status'] = 3001;
            return $ret;
        }
        //3是否支付成功了
        $this->CI->load->model("orderModel");
        $orderInfo = $this->CI->orderModel->orderDetailByReleaseId($obtainResult->user_id,$obtainResult->task_id);
        if($orderInfo){
            $orderNumber = $orderInfo->orderNumber;
        }
        else{
            $ret['status'] = 3014;
            return $ret;            
        }
        //订单金额不一致
        if($orderInfo->orderAmount!=$obtainResult->deposit){
            $ret['status'] = 3015;
            return $ret;                
        }
        //
        if($obtainResult->deposit<$obtainResult->left_deposit){
            $ret['status'] = 3016;
            return $ret;            
        }


        $this->CI->db->trans_start();

        //3修改状态
        $ret1 = $this->CI->db->set("status",2)->where("id",$data['obtainId'])->update('task_obtain');
        if(!$ret1){
            log_message("info","confirmTask,error,ret1");
            $ret['status'] = 1002;
            $this->CI->db->trans_rollback();
            return $ret;      

        }

        //4添加日志
        $temp = array(
            "task_obtain_id"=>$obtainResult->id,
            "status"=>2,
            "instruction"=>'提交给委托方',
        );
        $ret2 = $this->CI->db->insert('task_obtain_log', $temp);
        if(!$ret2){
            log_message("info","confirmTask,error,ret2");
            $ret['status'] = 1002;
            $this->CI->db->trans_rollback();
            return $ret;      
            
        }

        //5消息
        $this->CI->load->model("noticeModel");
        $this->CI->noticeModel->addNotice($obtainResult->user_id,2,$data['obtainId'],'您的任务已提交给委托方');
// 20181211 时坊确认，这里不退保证金，最后当成品确认以后，才退
        // //6退回保证金，微信退款，注意：如果已经退过一次，这里无需退款了（第一次通过，退回保证金，但是项目方未通过，又退回修改了）
        // $refundOrderByOrderInfo = $this->CI->orderModel->refundOrderByOrderId($obtainResult->user_id,$orderInfo->id,1);
        // log_message("info","refundOrderByOrderInfo:".json_encode($refundOrderByOrderInfo));
        // if(empty($refundOrderByOrderInfo->id)){

        //     $totalfee = $obtainResult->deposit;
        //     $refundfee = $obtainResult->left_deposit;
        //     log_message("info","totalfee:$totalfee,refundfee:$refundfee,orderNumber;$orderNumber,");
        //     if($refundfee>0){

        //         $refundOrder = $this->createRefundOrder($obtainResult->user_id,$orderInfo,$refundfee,1);
        //         log_message("info","refundOrder,:".json_encode($refundOrder));
        //         if(!$refundOrder){
        //             log_message("info","confirmTask,error,ret3");
        //             $ret['status'] = 1002;
        //             $this->CI->db->trans_rollback();
        //             return $ret;            
        //         }
        //         $this->CI->load->library('Wxpay/wxpay'); //公共 
        //         // $ordercode,$refundcode,$totalfee,$refundfee,$notifyurl
        //         // $refundNotifyUrl = $this->config->item('base_url') . '/index.php/order/notifyRefundOrder';        
        //         $payInfo = $this->CI->wxpay->wx_refund($orderNumber,$refundOrder['order_number'],$totalfee,$refundfee);
        //         log_message('info', 'adminConfirmTask:'.json_encode($payInfo));    
        //        // var_dump($payInfo);exit;
        //         if($payInfo['return_code']=='SUCCESS' && $payInfo['result_code']=='SUCCESS'){
        //             //退款成功
        //             $this->CI->load->model("orderModel");
        //             $this->CI->orderModel->confirmRefundOrder($refundOrder['order_number'],$payInfo);
        //         }
        //         else{
        //             $ret['status'] = 3020;
        //             $this->CI->db->trans_rollback();
        //             return $ret;                        
        //         }   
        //     }
        // }
        $this->CI->db->trans_complete();
        $ret['status'] = 0;
        return $ret;
        
    }  
    /**
     * [createRefundOrder 一个退款的订单/奖励的订单，都在user_reward_order中]
     * @param  [type] $orderInfo [原单信息，对应user_order中的记录]
     * @param  [type] $refundfee   [description]
     * @return [type]              [description]
     */
    public function createRefundOrder($userId,$orderInfo,$refundFee,$type){
        $data['user_id'] = $userId;
        $data['release_order_id'] = $orderInfo->id;
        $data['order_number'] = $this->createRefundOrderNumber($userId);
        $data['order_type'] = $type;
        $data['order_amount'] = $refundFee;
        $data['create_month'] = date("Y-m");
        
        $ret3 = $this->CI->db->insert('user_reward_order', $data);

        if($ret3)
            return $data;
        else
            return '';
    }

     /**
     * [createRefundOrderNumber description]
     * @return [type] [description]
     */
    private function createRefundOrderNumber($userId){
        if($userId>1000000){
            $userId = $userId;
        }
        else{
            $userId +=1000000;
        }
        $number = "RE".$userId.time().rand(1000,9999);
        return $number;
    }   

    /**
     * [adminDelayTask($admin_user_id,$data); description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function adminDelayTask($admin_user_id,$data){
        //1任务领取的状态
        $query = $this->CI->db->select('id,status,task_id,user_id,left_deposit')->get_where('task_obtain', ['id'=>$data['obtainId']], 1, 0); 
        $obtainResult = $query->row();  
        // echo  $this->CI->db->last_query();
        if(!$obtainResult || is_null($obtainResult)) {
            $ret['status'] = 3000;
            return $ret;
        }
        if($obtainResult->status!=3){ //用户尚未申请延期
            $ret['status'] = 3001;
            return $ret;
        }
        $left_deposit = $obtainResult->left_deposit;
        //2判断任务状态
        $query = $this->CI->db->select('id,status')->get_where('task', ['id'=>$obtainResult->task_id], 1, 0);
        $taskResult = $query->row();  
        if(!$taskResult || is_null($taskResult)) {
            $ret['status'] = 3000;
            return $ret;
        }
        if($taskResult->status!=1){ //不在进行中
            $ret['status'] = 3001;
            return $ret;
        }

        //3任务是否已经延期过
        $query = $this->CI->db->select('id,status')->get_where('task_obtain_log', ['task_obtain_id'=>$data['obtainId'],'status'=>4], 1, 0); 
        $obtainLogResult = $query->row();  
        if($obtainLogResult ) {
            $ret['status'] = 3011;
            return $ret;
        }
        

        //4修改状态
        $this->CI->db->trans_start();

        if(!empty($data['status']) && $data['status']==1){
            //不同意
            $newStatus = 0;
            $newDesc = '任务延期被拒绝，重新进入开发周期';
            $ret1 = $this->CI->db->set("status",$newStatus)->where("id",$data['obtainId'])->update('task_obtain');
            if(!$ret1){
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //5添加日志
            $temp = array(
                "task_obtain_id"=>$obtainResult->id,
                "status"=>$newStatus,
                "instruction"=>$newDesc,
            );
            $ret3 = $this->CI->db->insert('task_obtain_log', $temp);
            if(!$ret3){
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //6消息
            $this->CI->load->model("noticeModel");
            $this->CI->noticeModel->addNotice($obtainResult->user_id,2,$data['obtainId'],$newDesc);
             
        }
        else{
            // 同意            
            $newStatus = 4;
            $newDesc = '任务延期开发中';
            $ret1 = $this->CI->db->set("status",$newStatus)->where("id",$data['obtainId'])->update('task_obtain');
            if(!$ret1){
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }


            //5把延期的时间更新到task中
            $delayQuery = $this->CI->db->select('id,close_date,close_time,deduction')->order_by("id","desc")->get_where('task_obtain_log', ['task_obtain_id'=>$data['obtainId'],'status'=>3], 1, 0); 
            $delayObtainLogResult = $delayQuery->row();  
            if($delayObtainLogResult ) {
                $ret2 = $this->CI->db->set("close_date",$delayObtainLogResult->close_date)
                ->set("close_time",$delayObtainLogResult->close_time)->where("id",$obtainResult->task_id)->update('task');

                if(!$ret2){
                    $ret['status'] = 1002;
                    $this->CI->db->trans_rollback();
                    return $ret;
                }

                //扣除的保证金不足
                if($left_deposit<$delayObtainLogResult->deduction){
                    $ret['status'] = 3017;
                    $this->CI->db->trans_rollback();
                    return $ret;                
                }
            }
            else{
                $ret['status'] = 3018;
                $this->CI->db->trans_rollback();
                return $ret;

            }

            //4添加日志
            $temp = array(
                "task_obtain_id"=>$obtainResult->id,
                "status"=>$newStatus,
                "instruction"=>$newDesc,
            );
            $ret3 = $this->CI->db->insert('task_obtain_log', $temp);
            if(!$ret3){
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //5消息
            $this->CI->load->model("noticeModel");
            $this->CI->noticeModel->addNotice($obtainResult->user_id,2,$data['obtainId'],$newDesc);

            //6查看此次延期，是否有要扣除的保证金
            if($delayObtainLogResult && $delayObtainLogResult->deduction){

                $retDeduction = $this->CI->db->set("left_deposit",$left_deposit-$delayObtainLogResult->deduction)->where('id',$data['obtainId'])->update('task_obtain');
                
                if(!$retDeduction){
                    $ret['status'] = 1002;
                    $this->CI->db->trans_rollback();
                    return $ret;

                }
            }
            
        }
        $this->CI->db->trans_complete();
        $ret['status'] = 0;
        return $ret;
        
    } 

     /**
     * [adminCancelTask($admin_user_id,$data); 完全全新的任务]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function adminCancelTask($admin_user_id,$data){
        log_message('info', 'adminCancelTask');   
        //1任务领取的状态
        $query = $this->CI->db->select('id,status,task_id,user_id,deposit,left_deposit')->get_where('task_obtain', ['id'=>$data['obtainId']], 1, 0); 
        $obtainResult = $query->row();  
        // echo  $this->CI->db->last_query();
        log_message('info', 'adminCancelTask,one');   
        if(!$obtainResult || is_null($obtainResult)) {
            $ret['status'] = 3000;
            return $ret;
        }
        // echo $obtainResult->status;exit;
        if($obtainResult->status!=6){ //用户尚未申请取消
            $ret['status'] = 3001;
            return $ret;
        }
        $left_deposit = $obtainResult->left_deposit;
        log_message('info', 'adminCancelTask,two');   
        //2判断任务状态
        $query = $this->CI->db->select('*')->get_where('task', ['id'=>$obtainResult->task_id], 1, 0);
        $taskResult = $query->row();  
        if(!$taskResult || is_null($taskResult)) {
            $ret['status'] = 3000;
            return $ret;
        }
        if($taskResult->status!=1){ //不在进行中
            $ret['status'] = 3001;
            return $ret;
        }
        log_message('info', 'adminCancelTask,three');   
        //3是否申请了取消
        $delayQuery = $this->CI->db->select('id,deduction')->order_by("id","desc")->get_where('task_obtain_log', ['task_obtain_id'=>$data['obtainId'],'status'=>6], 1, 0); 
        $delayObtainLogResult = $delayQuery->row();  
        if($delayObtainLogResult ) {
            //扣除的保证金不足
            if($left_deposit<$delayObtainLogResult->deduction){
                $ret['status'] = 3017; 
                return $ret;                
            }
        }
        else{
            $ret['status'] = 3019; 
            return $ret;

        }
        log_message('info', 'adminCancelTask,three');   
        //3是否支付成功了
        $this->CI->load->model("orderModel");
        $orderInfo = $this->CI->orderModel->orderDetailByReleaseId($obtainResult->user_id,$obtainResult->task_id);
        if($orderInfo){
            $orderNumber = $orderInfo->orderNumber;
        }
        else{
            $ret['status'] = 3014;
            return $ret;            
        }



        //4修改状态
        $this->CI->db->trans_start();

        if(!empty($data['status']) && $data['status']==1){
            //不同意
            // 5
            $newTaskStatus = 0;
            $newDesc = '任务取消被拒绝，重新进入开发周期';
            $ret1 = $this->CI->db->set("status",$newTaskStatus)->where("id",$data['obtainId'])->update('task_obtain');
            if(!$ret1){
                log_message('info', 'adminCancelTask,staus error ret1:');     
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

             
            $ret2 = $this->CI->db->set("status",1)->where("id",$obtainResult->task_id)->update('task');
            if(!$ret2){
                log_message('info', 'adminCancelTask,staus error ret2:');     
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //6添加日志
            $temp = array(
                "task_obtain_id"=>$obtainResult->id,
                "status"=>$newTaskStatus,
                "instruction"=>$newDesc,
            );
            $ret3 = $this->CI->db->insert('task_obtain_log', $temp);
            if(!$ret3){
                log_message('info', 'adminCancelTask,staus error ret4:');   
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //7消息
            $this->CI->load->model("noticeModel");
            $this->CI->noticeModel->addNotice($obtainResult->user_id,2,$data['obtainId'],$newDesc);

          
            
        }
        else{

            $newTaskStatus = 7;
            $ret1 = $this->CI->db->set("status",$newTaskStatus)->where("id",$data['obtainId'])->update('task_obtain');
            if(!$ret1){

                log_message('info', 'adminCancelTask,staus error ret1:');     
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //5原任务改为已完结
            $ret2 = $this->CI->db->set("status",2)->where("id",$obtainResult->task_id)->update('task');
            if(!$ret2){
                log_message('info', 'adminCancelTask,staus error ret2:');     
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }
            if(isset($data['createNew'])&&$data['createNew']){
                //添加一个新的任务
                $temp = array(
                    "user_id"=>$taskResult->user_id,
                    "name"=>$taskResult->name,
                    "keyword"=>$this->createKeyWord(6),
                    "type"=>$taskResult->type,
                    "reward"=>$taskResult->reward,
                    "platform"=>$taskResult->platform,
                    "cover"=>$taskResult->cover,
                    "close_date"=>$taskResult->close_date,
                    "close_time"=>$taskResult->close_time,
                    "instruction"=>$taskResult->instruction,
                    "notes"=>$taskResult->notes,
                    "number_requirement"=>$taskResult->number_requirement,
                    "create_year"=>date("Y"),
                    "create_date"=>date("Y-m-d"),
                    "create_month"=>date("m"),
                );
                $ret3 = $this->CI->db->insert('task', $temp);
                if(!$ret3){
                log_message('info', 'adminCancelTask,staus error ret3:');   
                    $ret['status'] = 1002;
                    $this->CI->db->trans_rollback();
                    return $ret;
                }
            }

            //6添加日志
            $temp = array(
                "task_obtain_id"=>$obtainResult->id,
                "status"=>$newTaskStatus,
                "instruction"=>'任务已取消',
            );
            $ret3 = $this->CI->db->insert('task_obtain_log', $temp);
            if(!$ret3){
                log_message('info', 'adminCancelTask,staus error ret4:');   
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //7消息
            $this->CI->load->model("noticeModel");
            $this->CI->noticeModel->addNotice($obtainResult->user_id,2,$data['obtainId'],'任务已取消');

          
            //8更改剩余的保证金
            if($delayObtainLogResult && $delayObtainLogResult->deduction){
                $retDeduction = $this->CI->db
                    ->set("left_deposit",$left_deposit-$delayObtainLogResult->deduction)
                    ->where('id',$data['obtainId'])->update('task_obtain');
                if(!$retDeduction){
                log_message('info', 'adminCancelTask,staus error ret5:');   
                    $ret['status'] = 1002;
                    $this->CI->db->trans_rollback();
                    return $ret;

                }
            }

            //9退回保证金（注意：要扣除一部分，查询task_obtain_log中状态等于6的记录，看看扣了多少保证金）
            $totalfee = $obtainResult->deposit;
            log_message("info","adminCancelTask,obtainResult：".json_encode($obtainResult));
            $refundfee =  $left_deposit - $delayObtainLogResult->deduction;
            
            log_message('info', 'adminCancelTask,id:'.$obtainResult->user_id.",refundfee:$refundfee,orderinfo:".json_encode($orderInfo));   
            //超过0，才去退款
            if($refundfee>0){
                $refundOrder = $this->createRefundOrder($obtainResult->user_id,$orderInfo,$refundfee,1);
                if(!$refundOrder){
                    log_message('info', 'adminCancelTask,staus error ret6:');   
                    $ret['status'] = 1002;
                    $this->CI->db->trans_rollback();
                    return $ret;
                }
                $this->CI->load->library('Wxpay/wxpay'); //公共 
                // $ordercode,$refundcode,$totalfee,$refundfee,$notifyurl
                // $refundNotifyUrl = $this->config->item('base_url') . '/index.php/order/notifyRefundOrder';   
                log_message('info', "adminConfirmTask,orderNumber:$orderNumber,totalfee:$totalfee,refundfee:$refundfee");         
                $payInfo = $this->CI->wxpay->wx_refund($orderNumber,$refundOrder['order_number'],$totalfee,$refundfee);
                log_message('info', 'adminConfirmTask:'.json_encode($payInfo));    
                if($payInfo['return_code']=='SUCCESS' && $payInfo['return_code']=='SUCCESS'){
                    //退款成功,同样可以是这个接口，仅仅改订单表
                    $this->CI->load->model("orderModel");
                    $this->CI->orderModel->confirmRefundOrder($refundOrder['order_number'],$payInfo);
                }
                else{
                    $ret['status'] = 3020;
                    $this->CI->db->trans_rollback();
                    return $ret;                        
                }
            }
        }

        $this->CI->db->trans_complete();
        $ret['status'] = 0;
        return $ret;
        
    }    
        
    /**
     * [adminUpdateTask($admin_user_id,$data)，委托方是否同意方案]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function adminUpdateTask($admin_user_id,$data){
        //1任务领取的状态
        $query = $this->CI->db->select('id,status,task_id,user_id,deposit,left_deposit,student_award')->get_where('task_obtain', ['id'=>$data['obtainId']], 1, 0); 
        $obtainResult = $query->row();  
        // echo  $this->CI->db->last_query();
        if(!$obtainResult || is_null($obtainResult)) {
            $ret['status'] = 3000;
            return $ret;
        }
        // echo $obtainResult->status;exit;
        if($obtainResult->status!=2){ //尚未提交给委托方
            $ret['status'] = 3001;
            return $ret;
        }

        //2判断任务状态
        $query = $this->CI->db->select('*')->get_where('task', ['id'=>$obtainResult->task_id], 1, 0);
        $taskResult = $query->row();  
        if(!$taskResult || is_null($taskResult)) {
            $ret['status'] = 3000;
            return $ret;
        }
        if($taskResult->status!=1){ //不在进行中
            $ret['status'] = 3001;
            return $ret;
        }

        //4根据后台的状态
        if($data['status'] == 0){
            //委托方不同意方案，要继续修改
            $newTaskStatus = 5;
            $this->CI->db->trans_start();
            $ret1 = $this->CI->db->set("status",$newTaskStatus)->where("id",$data['obtainId'])->update('task_obtain');
            if(!$ret1){
                log_message('info', 'adminConfirmTask,status:1,ret1 error');    
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //6添加日志
            $temp = array(
                "task_obtain_id"=>$obtainResult->id,
                "status"=>$newTaskStatus,
                "instruction"=>$data['instruction'],
            );
            $ret3 = $this->CI->db->insert('task_obtain_log', $temp);
            if(!$ret3){
                log_message('info', 'adminConfirmTask,status:1,ret3 error');    
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //7消息
            $this->CI->load->model("noticeModel");
            $this->CI->noticeModel->addNotice($obtainResult->user_id,2,$data['obtainId'],$data['instruction']);

            $this->CI->db->trans_complete();
            $ret['status'] = 0;
        }
        else{
            //3是否支付成功了
            $this->CI->load->model("orderModel");
            $orderInfo = $this->CI->orderModel->orderDetailByReleaseId($obtainResult->user_id,$obtainResult->task_id);
            if($orderInfo){
                $orderNumber = $orderInfo->orderNumber;
            }
            else{
                $ret['status'] = 3014;
                return $ret;            
            }
            //订单金额不一致
            if($orderInfo->orderAmount!=$obtainResult->deposit){
                $ret['status'] = 3015;
                return $ret;                
            }
            //
            if($obtainResult->deposit<$obtainResult->left_deposit){
                $ret['status'] = 3016;
                return $ret;            
            }



            //委托方同意方案，触发打款操作，打款成功后，回调的接口把状态处理成9
            $newTaskStatus = 8;//审核通过
            $this->CI->db->trans_start();
            $ret1 = $this->CI->db->set("status",$newTaskStatus)->where("id",$data['obtainId'])->update('task_obtain');
            if(!$ret1){
                log_message('info', 'adminConfirmTask,status:2,ret1 error');   
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //5修改原任务状态为2
            $ret2 = $this->CI->db->set("status",2)->where("id",$obtainResult->task_id)->update('task');
            if(!$ret2){
                log_message('info', 'adminConfirmTask,status:2,ret2 error');   
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //6添加日志
            $temp = array(
                "task_obtain_id"=>$obtainResult->id,
                "status"=>$newTaskStatus,
                "instruction"=>$data['instruction'],
            );
            $ret3 = $this->CI->db->insert('task_obtain_log', $temp);
            if(!$ret3){
                log_message('info', 'adminConfirmTask,status:2,ret3 error');   
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }

            //6.1退保证金
            //6退回保证金，微信退款，注意：如果已经退过一次，这里无需退款了（第一次通过，退回保证金，但是项目方未通过，又退回修改了）
            $refundOrderByOrderInfo = $this->CI->orderModel->refundOrderByOrderId($obtainResult->user_id,$orderInfo->id,1);
            log_message("info","refundOrderByOrderInfo:".json_encode($refundOrderByOrderInfo));
            if(empty($refundOrderByOrderInfo->id)){
                $totalfee = $obtainResult->deposit;
                $refundfee = $obtainResult->left_deposit;
                log_message("info","totalfee:$totalfee,refundfee:$refundfee,orderNumber;$orderNumber,");
                if($refundfee>0){
                    $refundOrder = $this->createRefundOrder($obtainResult->user_id,$orderInfo,$refundfee,1);
                    log_message("info","refundOrder,:".json_encode($refundOrder));
                    if(!$refundOrder){
                        log_message("info","adminUpdateTask,error,ret3");
                        $ret['status'] = 1002;
                        $this->CI->db->trans_rollback();
                        return $ret;            
                    }
                    $this->CI->load->library('Wxpay/wxpay'); //公共 
                    // $ordercode,$refundcode,$totalfee,$refundfee,$notifyurl
                    // $refundNotifyUrl = $this->config->item('base_url') . '/index.php/order/notifyRefundOrder';        
                    $payInfo = $this->CI->wxpay->wx_refund($orderNumber,$refundOrder['order_number'],$totalfee,$refundfee);
                    log_message('info', 'adminUpdateTask:'.json_encode($payInfo));    
                   // var_dump($payInfo);exit;
                    if($payInfo['return_code']=='SUCCESS' && $payInfo['result_code']=='SUCCESS'){
                        //退款成功
                        $this->CI->load->model("orderModel");
                        $this->CI->orderModel->confirmRefundOrder($refundOrder['order_number'],$payInfo);
                    }
                    else{
                        $ret['status'] = 3020;
                        $this->CI->db->trans_rollback();
                        return $ret;                        
                    }   
                }
            }

            //7打款 (注意：任务奖励与学生奖励分开发放)
            $ret4 = $this->grantAward($obtainResult->user_id,$obtainResult,$obtainResult->task_id,1); //发放任务奖励  
            if($ret4){
                log_message('info', 'adminConfirmTask,status:2,ret4 error');   
                $ret['status'] = $ret4;
                $this->CI->db->trans_rollback();
                return $ret;
            }
            $ret5 = $this->grantAward($obtainResult->user_id,$obtainResult,$obtainResult->task_id,2); //发放学生奖励
            if($ret5){
                log_message('info', 'adminConfirmTask,status:2,ret5 error');   
                $ret['status'] = $ret5;
                $this->CI->db->trans_rollback();
                return $ret;
            }
            // 8查询是否通过别人邀请进来的，自己只能领取一次
            $userExtra = $this->extraInfo($obtainResult->user_id);
            if(!empty($userExtra->beinvited_code)){
                //是否已经领取过了，被邀请进来
                $this->CI->load->model("rewardOrderModel");
                $rewardOrder = $this->CI->rewardOrderModel->queryByUserIdAndType($obtainResult->user_id,4);
                if(!$rewardOrder){
                    //8.1自己没有领取过，可以领取一次
                    $ret6 = $this->grantAward($obtainResult->user_id,$obtainResult,$obtainResult->task_id,4); //发放
                    if($ret6){
                        log_message('info', 'adminConfirmTask,status:2,ret6 error');   
                        $ret['status'] = $ret6;
                        $this->CI->db->trans_rollback();
                        return $ret;
                    }
                    //
                    //8.2给邀请者一次奖励（能不能领，完全看被邀请人）
                    // 查询邀请人唯一标识
                    $inviteUserid = $this->queryInviteUserIdByUserid($obtainResult->user_id);
                    if($inviteUserid<0){
                        log_message('info', "adminConfirmTask,status:2,inviteUserid error,$inviteUserid");   
                        $ret['status'] = 3022;
                        $this->CI->db->trans_rollback();
                        return $ret;                        
                    }
                    $ret7 = $this->grantAward($inviteUserid,$obtainResult,$obtainResult->task_id,5); //发放
                    if($ret7){
                        log_message('info', 'adminConfirmTask,status:2,ret7 error');   
                        $ret['status'] = $ret7;
                        $this->CI->db->trans_rollback();
                        return $ret;
                    }
                }
                else{
                    //8.3 这里跟8.2互斥（文档上说的，如果邀请了别人，自己可以领一次，被邀请人也可以领一次，但是
                    //是2次任务，这里逻辑有问题，
                    //20181207 确认逻辑了，不用这里，用8.2
                    /**
                     * user_id   invite   be_invte
                     *  user_a     a        b
                     *  user_b     b        c
                     *  user_c     c        null
                     *
                     * c自注册，c邀请了b,b邀请了a，暂时都没有做任务
                     * 如果b这个时候做了任务，b是被c邀请的，要领一次奖励，b又邀请过a，这个时候，b做此次任务，要领两次奖励么？？
                     */
                    //

                }
            }  
            

            //10消息
            $this->CI->load->model("noticeModel");
            $this->CI->noticeModel->addNotice($obtainResult->user_id,2,$data['obtainId'],$data['instruction']);          
            //11改为已打款
            $newTaskStatusEnd = 9;
            $ret10 = $this->CI->db->set("status",$newTaskStatusEnd)->where("id",$data['obtainId'])->update('task_obtain');
            if(!$ret10){
                log_message('info', 'adminConfirmTask,status:2,ret10 error');   
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }  
             $temp = array(
                "task_obtain_id"=>$obtainResult->id,
                "status"=>$newTaskStatusEnd,
                "instruction"=>$data['instruction'],
            );
            $ret9 = $this->CI->db->insert('task_obtain_log', $temp);
            if(!$ret9){
                log_message('info', 'adminConfirmTask,status:2,ret9 error');   
                $ret['status'] = 1002;
                $this->CI->db->trans_rollback();
                return $ret;
            }
            $this->CI->db->trans_complete();
            $ret['status'] = 0;
        }


      
        return $ret;
        
    }    

    /**
     * [grantAward description]
     * @param  [type] $userId     [description]
     * @param  [type] $obtainInfo [description]
     * @param  [type] $taskId     [description]
     * @param  [type] $type       [1发放任务奖励，2发放学生奖励]
     * @return [type]             [description]
     */
    public function grantAward($userId,$obtainInfo,$taskId,$type){
        log_message("info","grantAward,userId:$userId,taskId:$taskId,type:$type,obtainInfo:".json_encode($obtainInfo));
        //1查询用户信息
        $baseInfo = $this->baseInfo($userId);
        if(!$baseInfo){
            return 2000;
        }
        $openid = $baseInfo->open_id;
        // echo $openid;exit;
        //2查询原单信息
        $this->CI->load->model("orderModel");
        $orderInfo = $this->CI->orderModel->orderDetailByReleaseId($userId,$taskId);
        //3查询原单是否进行过相应付款（存在一种情况，由于系统繁忙导致的退款失败，需要用原先的单号，去重新发送请求）
        $this->CI->load->model("rewardOrderModel");
        if($type==1){
            //3.1
            $rewardOrderInfo = $this->CI->rewardOrderModel->queryByUserIdAndRelaseId($userId,$orderInfo->id,$obtainInfo->left_deposit,2);
            // var_dump($rewardOrderInfo);exit;
            log_message("info","grantAward,rewardOrderInfo:".json_encode($rewardOrderInfo));
            if(!$rewardOrderInfo){
                $refundOrder = $this->createRefundOrder($userId,$orderInfo,$obtainInfo->left_deposit,2);
            }
            else{
                $refundOrder['user_id'] = $userId;
                $refundOrder['release_order_id'] = $orderInfo->id;
                $refundOrder['order_number'] = $rewardOrderInfo->order_number;
                $refundOrder['order_type'] = 2;
                $refundOrder['order_amount'] = $obtainInfo->left_deposit;                
            }
            log_message("info","grantAward,refundOrder:".json_encode($refundOrder));
            // var_dump($refundOrder);exit;
            $amount = $obtainInfo->left_deposit;
            $desc = '发放奖励';
        }
        else if($type==2){
            //3.1 
            if($obtainInfo->student_award){
                $rewardOrderInfo = $this->CI->rewardOrderModel->queryByUserIdAndRelaseId($userId,$orderInfo->id,$obtainInfo->left_deposit   ,3);
                log_message("info","grantAward2,rewardOrderInfo:".json_encode($rewardOrderInfo));
                if(!$rewardOrderInfo){
                    $refundOrder = $this->createRefundOrder($userId,$orderInfo,$obtainInfo->student_award,3);
                }
                else{
                    $refundOrder['user_id'] = $userId;
                    $refundOrder['release_order_id'] = $orderInfo->id;
                    $refundOrder['order_number'] = $rewardOrderInfo->order_number;
                    $refundOrder['order_type'] = 3;
                    $refundOrder['order_amount'] = $obtainInfo->student_award;   
                }

                $amount = $obtainInfo->student_award;
                $desc = '发放学生奖励';
            }
            else{
                return 0;
            }
        }
        else if($type==4){
             //3.1 
            $reward = $this->CI->config->item('inviteAward2');
            if($reward){
                $refundOrder = $this->createRefundOrder($userId,$orderInfo,$reward,4);
                $amount = $reward;
                $desc = '发放被邀请注册的奖励';
            }
            else{
                return 0;
            }
        }
        else if($type==5){
            $reward = $this->CI->config->item('inviteAward1');
            if($reward){
                $refundOrder = $this->createRefundOrder($userId,$orderInfo,$reward,5);
                $amount = $reward;
                $desc = '发放邀请别人注册的奖励';
            }
            else{
                return 0;
            }
        }
        else{
            log_message('info', 'grantAward,type is error');   
            return 1002;
        }
        // var_dump($refundOrder);exit;
        if(!$refundOrder){
            log_message('info', 'grantAward,refundOrder is error');   
            return 1002;          
        }
        //3发放奖励
        $extraInfo = $this->extraInfo($userId);
        if(!$extraInfo){
            return 2000;
        }
        //账号还未申请，这里先不触发企业付款20181207
        {
            // echo $amount>=0.01;exit;
            // if($amount>=0.01){
            //     log_message('info',"amount $amount");
            //     $this->CI->load->library('Wxpay/enpay'); //公共     
            //     $payXML = $this->CI->enpay->en_pay_package($openid,$refundOrder['order_number'],$amount, $extraInfo->id_name,$desc);
            //     // var_dump($payXML);exit;
            //     $payInfo = $this->CI->enpay->en_pay($payXML);
            //     $payInfo = $this->CI->enpay->FromXml($payInfo);
            //     log_message('info', 'grantAward,payInfo:'.json_encode($payInfo));    
            //    // var_dump($payInfo);exit;
            //     if($payInfo['return_code']=='SUCCESS' && $payInfo['result_code']=='SUCCESS'){
            //         //付款成功
            //         $this->CI->load->model("orderModel");
            //         $this->CI->orderModel->confirmRefundOrder($refundOrder['order_number'],$payInfo);
            //     }
            //     else{
            //         return 3020;                        
            //     }   
            // }
            // else{
            //     //如果本身奖励为0，直接成功
            //     $this->CI->load->model("orderModel");
            //     $this->CI->orderModel->confirmRefundOrder($refundOrder['order_number'],$payInfo);
            //     log_message('info','amount is low than 0.01');
            // }
        }
        {
            $this->CI->load->model("orderModel");
            $this->CI->orderModel->confirmRefundOrder($refundOrder['order_number'],array("key"=>"临时通过线下付款"));
        }
        return 0;
    }


    /**
     * [updateUserExtra]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function updateUserExtra($userId,$data){
        $array = array();
        if($data['nick']){
            $array['nickname'] = $data['nick'];
        }
        if(isset($data['head']) && $data['head']){
            $array['avatar'] = $data['head'];
        }
        if($array){
            $this->CI->db->set($array)->where("user_id",$userId)->update('user_extra');
        }
        return 0;
        
    } 
    /**
     * [queryInviteUserIdByUserid description]
     * @param  [type] $userid [description]
     * @return [type]         [description]
     */
    public function queryInviteUserIdByUserid($userid){
       //1查询当前用户邀请人
       $info = $this->CI->db->get_where('user_extra', array('user_id' => $userid),1, 0); 
       $result = $info->row();
       if($result){
           $beinvited_code = $result->beinvited_code;
           $info = $this->CI->db->get_where('user_base', array('account' => $beinvited_code),1, 0); 
           $result = $info->row();
           if($result){
                return $result->id;
           }
           else{
                return -2;
           }

       }    
       else{
            return -1;
       }
    }
}